package com.chwn.curiousdiary.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.Toast;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.bean.VersionBean;
import com.chwn.curiousdiary.service.DownloadAppService;
import com.chwn.harulib.util.ToastUtil;
import com.chwn.harulib.widget.AlertDialog;

/**
 * Created by Myshikin on 2017/6/8.
 */

public class UpdateAppUtils {

    public static void updataAPP(final VersionBean version, final Context context) {
        if (version == null || DiaryApplication.mInstance.currentVersionCode < version.getUpdateVersionCode()) {
            if (ServiceUtils.isServiceRunning(context, DownloadAppService.serviceName)) {
                ToastUtil.shortShowToast("升级服务已经启动,无需再次启动");
            } else {

                showUpdateDialog(version, context);
            }
        } else {
            Toast.makeText(context, "当前已是最新版本", Toast.LENGTH_SHORT).show();
        }
    }

    public static void showUpdateDialog(final VersionBean version, final Context context) {
        AlertDialog.Builder buile = new AlertDialog.Builder(context)
                .setTitle("更新提示").setMessage("好奇日记" + version.getUpdateVersionName() + "版本已经发布，快去\n" +
                        "体验新功能吧").setPositiveButton
                        ("立即更新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                Intent it = new Intent(context,
                                        DownloadAppService.class);
                                it.putExtra(DownloadAppService.SERVICRINTENTURL,
                                        version.getDownloadUrl());
                                it.putExtra(DownloadAppService.SERVACESHARENAME, 0);
                                context.startService(it);
                            }
                        })
                .setNegativeButton("下次再说", null);
        Dialog dialog = buile.create();
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }
}
